package ucd.csi.comp30220.fall2011.oteop.collision;

import java.util.Hashtable;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import ucd.csi.comp30220.fall2011.oteop.OTEOP;
import ucd.csi.comp30220.fall2011.oteop.util.EndPoint;
import ucd.csi.comp30220.fall2011.oteop.util.ServiceFinder;

/**
 * Publishes data to a JMS topic
 * 
 * @author David Haddock
 */
public class CollisionPublisher {
    
    private MessageProducer sender;
    private Session session;
    
    public CollisionPublisher() throws Exception {
        long timeout = 10*1000;
        EndPoint endPoint = ServiceFinder.findService(
                OTEOP.JMDNS_TYPE_TCP_LOCAL, Collision.JMDNS_SUB_TYPE, "collision", timeout);
        if (endPoint == null)
            throw new Exception("Failed to get an implementation of Collision in " + timeout + "ms");
        String providerUrl = "tcp://" +endPoint.getHost() +":" +endPoint.getPort();
        
        Hashtable<String, String> properties = new Hashtable<String, String>();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, OTEOP.JAVA_NAMING_FACTORY_INITIAL);
        properties.put(Context.PROVIDER_URL, providerUrl);
        Context context = new InitialContext(properties);
        ConnectionFactory factory = (ConnectionFactory) context.lookup("ConnectionFactory");
        Connection connection = factory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = (Destination) context.lookup("topic1");
        sender = session.createProducer(destination);
		System.out.println("JMS Publisher to: " +providerUrl);
    }

	/**
	 * Publish Collision info to a topic via JMS
	 * @param info the collision info
	 * @throws NamingException If the JMS server isn't running
	 * @throws JMSException If a connection cannot be made to the server
	 */
	public void publish(Collision info) throws Exception
	{
        ObjectMessage message = session.createObjectMessage((CollisionInfo) info);
		sender.send(message);
	}
}
